//forwardfeed 宏
#define BLOCK_SIZE {{ block_size }}
#define BATCH_SIZE {{ batch_size }}
#define INV_BATCH_SIZE {{ inv_batch_size }}
#define PRE_Z_WIDTH {{ pre_z_width }}
#define W_WIDTH {{ w_width }}
#define POST_Z_WIDTH {{ post_z_width }}


// Miscellaneous functions
__device__ float  sigmoid(float z)
{
    //The sigmoid function.
    return 1.0/(1.0 + expf(-z));
}

__device__ float  sigmoid_prime(float z)
{
    //Derivative of the sigmoid function.
    return sigmoid(z)*(1-sigmoid(z));
}

__device__ float  sigmoid_prime_a(float a)
{
    //Derivative of the sigmoid function.
    return a*(1-a);
}

__device__ float logit(float a)
{
    return logf(a/(1-a));
}

__global__ void feedforward(float *pre_a,float *wl,float *bl,float *al)
{
    // Block index
    int bx = blockIdx.x;
    int by = blockIdx.y;

    // Thread index
    int tx = threadIdx.x;
    int ty = threadIdx.y;

    // Index of the first sub-matrix of A processed by the block
    int aBegin = PRE_Z_WIDTH * blockDim.y * by;

    // Index of the last sub-matrix of A processed by the block
    int aEnd   = aBegin + PRE_Z_WIDTH - 1;

    // Step size used to iterate through the sub-matrices of A
    int aStep  = blockDim.x;

    // Index of the first sub-matrix of B processed by the block
    int bBegin = blockDim.x * bx;

    // Step size used to iterate through the sub-matrices of B
    int bStep  = blockDim.y * W_WIDTH;

    // Csub is used to store the element of the block sub-matrix
    // that is computed by the thread
    float Csub = 0;

    // Loop over all the sub-matrices of A and B
    // required to compute the block sub-matrix
    for (int a = aBegin, b = bBegin;
            a <= aEnd;
            a += aStep, b += bStep) {
        // Declaration of the shared memory array As used to
        // store the sub-matrix of A
        __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];

        // Declaration of the shared memory array Bs used to
        // store the sub-matrix of B
        __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];

        // Load the matrices from device memory
        // to shared memory; each thread loads
        // one element of each matrix
        As[ty][tx] = pre_a[a + PRE_Z_WIDTH * ty + tx];
        Bs[ty][tx] = wl[b + W_WIDTH * ty + tx];

        // Synchronize to make sure the matrices are loaded
        __syncthreads();

        // Multiply the two matrices together;
        // each thread computes one element
        // of the block sub-matrix
#pragma unroll

        for (int k = 0; k < BLOCK_SIZE  ; ++k) {
            Csub += As[ty][k] * Bs[k][tx];
        }

        // Synchronize to make sure that the preceding
        // computation is done before loading two new
        // sub-matrices of A and B in the next iteration
        __syncthreads();
    }

    //提取出b
    __shared__ float bs[BLOCK_SIZE];
    if(ty == 0)
    {
        bs[tx] = bl[BLOCK_SIZE * bx + tx];
    }

    __syncthreads();

    // Write the block sub-matrix to device memory;
    // each thread writes one element
    int block = W_WIDTH * blockDim.y * by + blockDim.x * bx;
    int threadPos = block + W_WIDTH * ty + tx;
    al[threadPos] = sigmoid(Csub + bs[tx]);
}

__global__ void backprop(/*batchsize n*/float *al ,/*n l*/float *post_w,/*batchsize l*/float *post_delta,/*output batchsize n*/float *delta)
{
        // Block index
        int bx = blockIdx.x;
        int by = blockIdx.y;
    
        // Thread index
        int tx = threadIdx.x;
        int ty = threadIdx.y;
    
        // post_w矩阵
        int aBegin = POST_Z_WIDTH * blockDim.y * bx;
        int aEnd   = aBegin + POST_Z_WIDTH - 1;

        int Step  = blockDim.x;
        //post_delta矩阵
        int bBegin = POST_Z_WIDTH * blockDim.y * by;

        float Csub = 0;
    
        for (int a = aBegin, b = bBegin;
                a <= aEnd;
                a += Step, b += Step) {
            //临时缓存
            __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
    
            __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
    
            As[ty][tx] = post_w[a + POST_Z_WIDTH * ty + tx];
            Bs[ty][tx] = post_delta[b + POST_Z_WIDTH * ty + tx];
    
            //
            __syncthreads();
    
    #pragma unroll
    
            for (int k = 0; k < BLOCK_SIZE  ; ++k) {
                Csub += As[tx][k] * Bs[ty][k];
                //Csub += 1;//Bs[ty][k];
            }
    
            __syncthreads();
        }
        int width = blockDim.x * gridDim.x;
        int blockPos = width * blockDim.y * by + blockDim.x * bx;
        int threadPos = blockPos + width * ty + tx;
        float _a = al[threadPos];
        delta[threadPos] = Csub * sigmoid_prime_a(_a);
}
__device__ float cost_derivative(float a,float y)
{
    return a - y;
}

//最后一层bp
__global__ void bplast(float *al ,float *y,/*output*/float *delta)
{
    // Block index
    int bx = blockIdx.x;
    int by = blockIdx.y;

    // Thread index
    int tx = threadIdx.x;
    int ty = threadIdx.y;

    int width = blockDim.x * gridDim.x;
    int blockPos = width * blockDim.y * by + blockDim.x * bx;
    int threadPos = blockPos + width * ty + tx;

    float a = al[threadPos];

    delta[threadPos] = cost_derivative(a , y[threadPos]) * sigmoid_prime_a(a);
}

//更新w和b
__global__ void updatewb(/*batchsize m*/float *pre_a, float/*batchsize n*/ *delta, /*output m n*/float *w,/*output n*/float *b, float eta)
{
    // Block index
    int bx = blockIdx.x;
    int by = blockIdx.y;

    // Thread index
    int tx = threadIdx.x;
    int ty = threadIdx.y;

    //矩阵pre_z 和矩阵delta 的列向量相乘
    int aBegin = BLOCK_SIZE * by;
    int aEnd   = aBegin + PRE_Z_WIDTH * BATCH_SIZE - 1;

    int aStep  = PRE_Z_WIDTH * BLOCK_SIZE;
    //post_delta矩阵
    int bBegin = BLOCK_SIZE * bx;
    int bStep = W_WIDTH * BLOCK_SIZE;

    float Wsub = 0;
    float Bsub = 0;

    for (int a = aBegin, b = bBegin;
            a <= aEnd;
            a += aStep, b += bStep) {
        //临时缓存
        __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];

        __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];

        //取列向量
        As[ty][tx] = pre_a[a + PRE_Z_WIDTH * tx + ty];
        Bs[ty][tx] = delta[b + W_WIDTH * tx + ty];

        //
        __syncthreads();

#pragma unroll

        for (int k = 0; k < BLOCK_SIZE  ; ++k) {
            Wsub += As[ty][k] * Bs[tx][k];
            //Csub += 1;//Bs[ty][k];
            if(by == 0 && ty == 0)
            {
                Bsub +=  Bs[tx][k];
            }
        }

        __syncthreads();
    }

    Wsub = Wsub * INV_BATCH_SIZE * eta;
    Bsub = Bsub * INV_BATCH_SIZE * eta;

    int width = blockDim.x * gridDim.x;
    int blockPos = width * blockDim.y * by + blockDim.x * bx;
    int threadPos = blockPos + width * ty + tx;
    w[threadPos] = w[threadPos] - Wsub;

    if(by == 0 && ty == 0)
    {
        b[threadPos] = b[threadPos] - Bsub;
    }
}